package com.example.essayjoke.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.webkit.WebView;

import com.example.essayjoke.R;

/**
 * 一个文字两种颜色
 */
public class ColorTrackTextView extends androidx.appcompat.widget.AppCompatTextView {
    private Paint originPaint;
    private Paint changePaint;

    public ColorTrackTextView(Context context) {
        this(context, null);
    }

    public ColorTrackTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorTrackTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView);

        int originColor = array.getColor(R.styleable.ColorTrackTextView_originColor, getTextColors().getDefaultColor());
        int changeColor = array.getColor(R.styleable.ColorTrackTextView_changeColor, getTextColors().getDefaultColor());

        originPaint = getPaintByColor(originColor);
        changePaint = getPaintByColor(changeColor);
        array.recycle();
    }

    private Paint getPaintByColor(int color) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(color);
        // 防抖动
        paint.setDither(true);
        // 字体大小
        paint.setTextSize(getTextSize());
        return paint;
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 不使用系统的画法
        //super.onDraw(canvas);

        //canvas.clipRect(); 裁剪区域

        String text = getText().toString();
        // 获取字体的宽度
        Rect textRect = new Rect();
        changePaint.getTextBounds(text, 0, text.length(), textRect);
        int x = getWidth() / 2 - textRect.width();
        // 基线
        Paint.FontMetricsInt fontMetricsInt = changePaint.getFontMetricsInt();
        int dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
        int baseLine = getHeight() / 2 + dy;
        canvas.drawText(text, x, baseLine, changePaint);
    }
}
